#include"Stack.h"
void Init(Stack* ps)
{
    assert(ps);
    ps->a = NULL;
    //如果top初始化为-1:那么就需要先++,然后再放数据,当前栈中元素个数为:top+1
    //如果top初始化为0,那么先放数据,然后top++,top代表的就是当前栈中元素个数
    ps->top = 0;
    ps->capacity = 0;
}
void push(Stack* ps,DataType x)
{
  assert(ps);
  //先检查容量,是否需要扩容
  if(ps->capacity == ps->top)
  {
     int newcapacity = ps->capacity == 0 ? 4:ps->capacity*2;
     DataType* tmp = (DataType*)realloc(ps->a,sizeof(DataType)*newcapacity); 
     if(NULL == tmp)
     {
        perror("realloc:");
        exit(1);
     }
     ps->a = tmp;
     ps->capacity = newcapacity;
  }
  ps->a[ps->top] = x;
  ps->top++;
}
void pop(Stack* ps)
{
  assert(ps);
  assert(!empty(ps));
  ps->top--;
}
bool empty(Stack* ps)
{
  assert(ps);
  return ps->top == 0;
}
size_t size(Stack* ps)
{
  assert(ps);
  return ps->top;
}
DataType top(Stack* ps)
{
  assert(ps);
  return ps->a[ps->top-1];
}
void Destory(Stack* ps)
{
  free(ps->a);
  ps->a = NULL;
  ps->capacity = ps->top= 0;
}
